<?php

namespace app\api\controller\v2;

use app\api\controller\Common;

define('WXPAY', ROOT_PATH . "wechatpay" . DS);
require ROOT_PATH . 'wechatpay/lib/WxPay.Config.php';

use app\common\service\WXUtils;
use think\Log;

class Redpacket extends Common
{
    var $modelDb;

    public function _initialize()
    {
        parent::_initialize();
        $this->modelDb = model("Redpacket");
    }

    /**
     * 检查该用户有没有领取红包的权限
     */
    public function checkredpacket()
    {
        $returndata = [
            'redpacketable' => 0
        ];
        if (!isset($this->postData['code']) || !isset($this->postData['userid'])) {
            $returndata['redpacketable'] = 0;
            return $this->app_success($returndata);
        }
        $code = $this->postData['code']; // 阅读者的wxappcode
        $userid = $this->postData['userid']; // 分享人的id
        $shareuser = model("AdminUser")->where('userid', $userid)->field('vip,vipendtime')->find();
        Log::record('info:::' . var_export($shareuser['vip'] . '###' . $shareuser['vipendtime'], true), 'info');
        if ($shareuser['vip'] || $shareuser['vipendtime']) { // 如果分享人已经是荣耀会员或曾经是荣耀会员，则没有领取红包的权限
            $returndata['redpacketable'] = 0;
            return $this->app_success($returndata);
        }
        $count = model('Redpacket')->where('userid', $userid)->count();
        if ($count >= config('ARTICLEMAXNUM')) { // 分享人分享的次数大于上限，阅读者不再有领取红包的权限
            $returndata['redpacketable'] = 0;
            return $this->app_success($returndata);
        }
        if ($code) {
            $wxutils = new WXUtils();
            $openid = $wxutils->get_wechat_openid($this->postData['code']);
            if ($openid) {
                $user = model("AdminUser")->where('openid', $openid)->field('vip,vipendtime')->find();
                if ($user) { // 此用户已经注册
                    if ($user['vip'] || $user['vipendtime']) { // 此用户为荣耀会员或曾经是荣耀会员，则没有领取红包的权限
                        $returndata['redpacketable'] = 0;
                        return $this->app_success($returndata);
                    } else {
                        $check = $this->checkredpacketorder($openid, $userid);
                        if ($check) { // 已经领取过该分享人的红包
                            $returndata['redpacketable'] = 0;
                            return $this->app_success($returndata);
                        } else {
                            $returndata['redpacketable'] = 1;
                            $returndata['openid'] = $openid;
                            return $this->app_success($returndata);
                        }
                    }
                } else { // 此用户没有注册过
                    $check = $this->checkredpacketorder($openid, $userid);
                    if ($check) { // 已经领取过该分享人的红包
                        $returndata['redpacketable'] = 0;
                        return $this->app_success($returndata);
                    } else {
                        $returndata['openid'] = $openid;
                        $returndata['redpacketable'] = 1;
                        return $this->app_success($returndata);
                    }
                }
            } else {
                $returndata['redpacketable'] = 0;
                return $this->app_success($returndata);
            }
        } else {
            $returndata['redpacketable'] = 0;
            return $this->app_success($returndata);
        }
    }

    // 检查该用户有没有领取过分享人分享的红包
    private function checkredpacketorder($openid, $userid)
    {
        $user = $this->modelDb->where('openid', $openid)->where('userid', $userid)->find();
        if ($user) {
            return true;
        } else {
            return false;
        }
    }

    public function createredpacket()
    {
        $openid = $this->postData['openid'];
        $avatar = $this->postData['avatar'];
        $oidnickname = $this->postData['nickname'];
        $userid = $this->postData['userid'];
        $articleid = $this->postData['articleid'];
        $amount = mt_rand(30, 40);
        $param = [
            'openid' => $openid,
            'amount' => $amount,
            'desc' => '助力红包'
        ];
        require_once WXPAY . "lib/WxPay.Api.php";
        require_once WXPAY . "lib/WxPay.Config.php";
        $wxPayApi = new \WxPayApi();
        $wxdatabase = new \WxPayDataBase();
        $wxconfig = new \WxPayConfig();
        $result = $wxPayApi::createRedpacketParam($param);
//        return $this->app_success($result);
        //*******************************************************************************//
        //*******************************************************************************//
        //*******************************************************************************//
        //*******************************************************************************//
        //*******************************************************************************//
//        $result = [
//            "code" => 1,
//            "return_code" => "SUCCESS",
//            "return_msg" => [],
//            "mch_appid" => "wx6b366da92930ca73",
//            "mchid" => "1527048741",
//            "nonce_str" => "5dsveqjkefd8o4ztik6nems1611wfipv",
//            "result_code" => "SUCCESS",
//            "partner_trade_no" => "152704874120200724xkgwx9r8w7",
//            "payment_no" => "10101039545952007244384534647061",
//            "payment_time" => "2020-07-24 17:41:37"
//        ];
        if ($result['code']) {
            $data = [
                'openid' => $openid,
                'oidnickname' => $oidnickname,
                'avatar' => $avatar,
                'userid' => $userid,
                'amount' => $amount,
                'articleid' => $articleid,
                'datetime' => SYS_TIME
            ];
            $id = model('redpacket')->save($data);
            if ($id) {
                return $this->app_success();
            } else {
                return $this->app_error();
            }
        } else {
            return $this->app_error($result['msg']);
        }
    }

    public function shareProgress()
    {
//        $list = $this->modelDb->where('userid', $this->uinfo['userid'])->field('openid ,oidnickname')->find();
        $list = $this->modelDb->list_data(['userid' => $this->uinfo['userid']], 0, 0, 'openid as id, oidnickname as nickname,avatar,datetime');
        $count = count($list);
        $total = config('ARTICLEMAXNUM');
        if ($count > $total) {
            $count = $total;
        }
        $returndata = [
            'count' => $count,
            'total' => $total,
            'percent' => intval($count / $total * 100),
            'list' => $list
        ];
        return $this->app_success($returndata);
    }
}